﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZMA._controls;
using BIZModel;
using BL.BIZControls;
using BIZMA.BL.Security;

namespace BIZMA._controls.Demo
{
    public partial class Edit_Company : BIZEditControl, IBIZControlDefaultMethods
    {
        #region default
        public void DefaultListLoad()
        {
            throw new NotImplementedException();
        }

        public void DefaultListLoad(Guid Id, string loadByType)
        {
            throw new NotImplementedException();
        }

        public void DefaultEditNew()
        {
            NewCompany();
        }

        public void DefaultEditNew(Guid Id, string editByType)
        {
            throw new NotImplementedException();
        }

        public void DefaultEditLoad(Guid Id)
        {
            LoadCompany(Id);
        }


        #endregion

        //Properties för att hålla reda på om en dialog kan öppnas eller om den redan är öppen i en underliggande dialog
        private bool CanAddEmployeeDialog { get { return ViewState["CanAddEmployeeDialog"] != null ? (bool)ViewState["CanAddEmployeeDialog"] : true; } set { ViewState["CanAddEmployeeDialog"] = value; } }
        private bool CanAddPermissionDialog { get { return ViewState["CanAddPermissionDialog"] != null ? (bool)ViewState["CanAddPermissionDialog"] : true; } set { ViewState["CanAddPermissionDialog"] = value; } }

        public bool FuncEditEmployees { get; set; }
        public bool FuncEdit { get; set; }


        #region This Dialog
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack || !InitLoaded)
            {
                InitLoaded = true;

                //Gör sådant som man gör på pageload här typ fyll "statisk" dropdown med värden mm 

            }
        }


     

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //här gör man alla init inställningar typ lägga till eventhandlers och annat som styr sidan

            if (ContainerControl != null)
            {
                ContainerControl.Title = "Administrera företag";
                ContainerControl.ButtonsClick += new ButtonsHandler(ContainerControl_ButtonsClick);
                ContainerControl.ShowButtons(true, true, true, true);

                if (ModalContainerControl != null)
                {
                    ModalContainerControl.Width = 700;
                    ModalContainerControl.Height = 470;
                    
                }                

                //Måste ha unika valgroup så att inte olika kontoller triggar varandras valideringar
                valEmail.ValidationGroup = ContainerControl.ValGroupSave;
                valName.ValidationGroup = ContainerControl.ValGroupSave;
                valWebSite.ValidationGroup = ContainerControl.ValGroupSave;
                selBusinessType.ReqValidationGroup = ContainerControl.ValGroupSave;
              
            }

            //Kontrollera om ytterligare dialoger kan öppnas eller om de redan är öppnade i underliggade dialoger
            CanAddEmployeeDialog = mcEmployee.CanAddPopupControl(BIZControl.DemoEmployee);
            CanAddPermissionDialog = mcPermission.CanAddPopupControl(BIZControl.ObjectRoleList);


            //Regga alla event här istället för i sidan eftersom det funkar så dåligt med automatisering av eventstödet i VS
            btnEmployees.Command += new CommandEventHandler(btnEmployees_Click);
            btnPermission.Command += new CommandEventHandler(btnPermission_Command);


           
        }



        void ContainerControl_ButtonsClick(object sender, ActionType actionType)
        {
            if (actionType == ActionType.Save || actionType == ActionType.SaveClose)
            {
                Save();
            }
            else if (actionType == ActionType.Delete)
            {
                Delete();
            }
        }


        #endregion

        #region methods this dialog
        /// <summary>
        /// Den här funktionen aktiverar inativerar knappar som kräver att formuläret har sparats/laddats och det finns data som 
        /// knappen kan använda ex Man kan inte öppna en planering för ett projekt om inte projektet har skapats/laddats först
        /// </summary>
        private void ToggleButtons()
        {


            if (!CanAddEmployeeDialog)
            {
                BaseBL.BtnOpenEnabled(btnEmployees, false, ViewState);
            }
            if (!CanAddPermissionDialog)
            {
                BaseBL.BtnOpenEnabled(btnPermission, false, ViewState);
            }
            
            if (CurrentId != Guid.Empty)
            {
                //man måste förs checka så att inte knappen är avaktiverad pga att dialogen redan finns i underliggande dialog
                if (CanAddEmployeeDialog)
                {
                    BaseBL.BtnNeedsDataEnabled(btnEmployees, true, ViewState);
                }
                if (CanAddPermissionDialog)
                {
                    BaseBL.BtnNeedsDataEnabled(btnPermission, true, ViewState);
                }
            }
            else
            {
                if (CanAddEmployeeDialog)
                {
                    BaseBL.BtnNeedsDataEnabled(btnEmployees, false, ViewState);
                }
                if (CanAddPermissionDialog)
                {
                    BaseBL.BtnNeedsDataEnabled(btnPermission, false, ViewState);
                }
            }
        }

        /// <summary>
        /// Metod för att tömma sida och aktivera läge för att skapa nytt
        /// </summary>
        public void NewCompany()
        {
            //CurrentProjectId = Guid.Empty;
            LoadCompany(Guid.Empty);
        }

        /// <summary>
        /// ladda formuläret med existerande data för att ex uppdatera
        /// </summary>
        /// <param name="someVal"></param>
        public void LoadCompany(Guid companyId)
        {   InitLoaded = true;
            CurrentId = companyId;


            if (companyId != Guid.Empty)
            {
                BIZMAEntities ent = BaseBL.GetEnt();

                    
                
               FuncEditEmployees = ent.Security_HasFunction(BaseBL.UserId, companyId, typeof(DemoCompany).FullName, SecurityBL.OBJFUNCTION_COMPANY_EDITEMPLOYEES).First().Value;

                
               
                BIZModel.DemoCompany company = ent.DemoCompanies.FirstOrDefault(q => q.CompanyId == companyId);

                txtName.Text = company.Name;
                txtDescription.Text = company.Description;
                selBusinessType.SelectedId = company.BusinessTypeId;
                txtWebSite.Text = company.WebSite;
                txtEmail.Text = company.Email;
                txtPhone.Text = company.Phone;
               
            }
            else
            {
                txtName.Text = "";
                txtDescription.Text = "";
                selBusinessType.SelectedId = Guid.Empty;
                txtWebSite.Text = "";
                txtEmail.Text = "";
                txtPhone.Text = "";
               
            }

            ToggleButtons();
        }


        private void Save()
        {
            //SAVE
            if (Page.IsValid)
            {

                BIZMAEntities ent = BaseBL.GetEnt();
                BIZModel.DemoCompany company = null;

                //ent.SaveChanges();
                if (CurrentId == Guid.Empty)
                {
                    CurrentId = Guid.NewGuid();
                    company = DemoCompany.CreateDemoCompany(CurrentId, 0, txtName.Text, selBusinessType.SelectedId);
                    company.Description = txtDescription.Text;
                    company.WebSite = txtWebSite.Text;
                    company.Email = txtEmail.Text;
                    company.Phone = txtPhone.Text;
                    ent.AddToDemoCompanies(company);
                }
                else
                {
                    company = ent.DemoCompanies.FirstOrDefault(q => q.CompanyId == CurrentId);
                    company.Name = txtName.Text;
                    company.Description = txtDescription.Text;
                    company.BusinessTypeId = selBusinessType.SelectedId;
                    company.WebSite = txtWebSite.Text;
                    company.Email = txtEmail.Text;
                    company.Phone = txtPhone.Text;



                }


                ent.SaveChanges();

                //Ändra aktivering av knappar efter sparning
                LoadCompany(CurrentId);
            }
        }

        private void Delete()
        {
            BIZMAEntities ent = BaseBL.GetEnt();
            BIZModel.DemoCompany company = ent.DemoCompanies.FirstOrDefault(q => q.CompanyId == CurrentId);
            ent.DeleteObject(company);
            ent.SaveChanges();

        }
        #endregion


        #region MEMBERS DIALOG


        protected void btnEmployees_Click(object sender, EventArgs e)
        {
            mcEmployee.AddControl(BIZControl.DemoEmployeeList);
            if (mcEmployee.ContainedControlExists)
            {
                ((List_Employees)mcEmployee.ContainedControl).LoadByCompany(CurrentId);
                mcEmployee.ModalOpen();

            }
        }

        void btnPermission_Command(object sender, CommandEventArgs e)
        {
            mcPermission.AddDefaultListLoad(BIZControl.ObjectRoleList, CurrentId, typeof(BIZModel.DemoCompany).FullName);
        }

        #endregion




    }
}